from client import MCPClient
import time
import threading
import json


def start_sse_listener(client):
    sse_stream = client.open_sse_stream()
    if sse_stream:
        print(f"SSE流连接成功")
        try:
            for line in sse_stream.iter_lines(chunk_size=1, decode_unicode=True):
                if line.startswith("event: "):
                    event_type = line[7:]
                elif line.startswith("data: "):
                    data_str = line[6:]
                    data = json.loads(data_str)
                    if event_type == "notifications/progress":
                        client.handle_progress_notification(data)
                    else:
                        print(f"未知的事件类型:{event_type} data:{data}")
        except Exception as e:
            print(f"监听SSE流发生了错误:{str(e)}")


def progress():
    client = MCPClient("http://localhost:8000")
    try:
        if not client.initialize():
            print(f"初始化连接失败")
            return
        sse_listener_thread = threading.Thread(
            target=start_sse_listener, args=(client,), daemon=True
        )
        sse_listener_thread.start()
        tools = client.list_tools()
        print(f"当前可用工具:{[tool['name'] for tool in tools]}")
        start_time = time.time()
        result = client.call_tool("calculate", {"expression": "10+20*3"})
        end_time = time.time()
        if result:
            content = result.get("content", [])
            if content:
                print(f"计算的结果:{content[0].get('text','')}")
                print(f"执行时间为:{end_time- start_time:.2f}")
        start_time = time.time()
        result = client.call_tool(
            "calculate", {"expression": "10+20*3"}, enable_progress=True
        )
        end_time = time.time()
        if result:
            content = result.get("content", [])
            if content:
                print(f"计算的结果:{content[0].get('text','')}")
                print(f"执行时间为:{end_time- start_time:.2f}")
        sse_listener_thread.join()

    except Exception as e:
        print(f"进度通知发生错误:{str(e)}")


def main():
    progress()


if __name__ == "__main__":
    main()
